package com.tech.koufu.ui.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.inqbarna.tablefixheaders.TableFixHeaders; 
import com.tech.koufu.MyApplication;
import com.tech.koufu.R;
import com.tech.koufu.action.OnTableItemClickIf;
import com.tech.koufu.model.EntrustStock;
import com.tech.koufu.model.UserStocks;
import com.tech.koufu.tools.CookieStringRequest;
import com.tech.koufu.tools.KouFuTools;
import com.tech.koufu.tools.Statics;
import com.tech.koufu.ui.adapter.EntrustStocksAdapter;
import com.tech.koufu.ui.adapter.EntrustTableAdapter;
import com.tech.koufu.ui.widiget.CofDialog;
import com.umeng.analytics.MobclickAgent;

import extras.com.handmark.pulltorefresh.library.PullToRefreshListView;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 
 * @ClassName: EntrustListActivity
 * @Description: 委托撤单列表
 * @author 123
 * @date 2015年3月29日 下午12:02:11
 */
public class EntrustListActivity extends Activity implements OnClickListener ,Callback{
	private static final String TAG = EntrustListActivity.class.getName();
	private Context mContext;
	private TextView pageTitle, tabStockSn, tv_title;
	private ArrayList<EntrustStock> mUserStocks;
	private ArrayList<EntrustStock> datas;
	private PullToRefreshListView mPullToRefreshListView;
	private ListView actualListView;
	private EntrustStocksAdapter mAdapter;
	private RequestQueue mQueue;
	private MyApplication myApp;
	StringRequest stringRequest;
	CookieStringRequest cookieStringRequest;
	CookieStringRequest cdStringRequest;
	Button cxButton;
	TableFixHeaders tableFixHeaders ;
	private String[][] table;
	private final String[] heads = new String[]{"撤单","状态","股票名称","操作类型","委托价格","委托数量","委托时间"};

	private EntrustTableAdapter<String> entrustTableAdapter; 
	private ArrayList<String> cdlist;
	private Handler mHandler;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_entrust_list);
		mContext = this;
		initView();
	}
	
	 @Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		MobclickAgent.onResume(mContext);
	}
	 
	 @Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		MobclickAgent.onPause(mContext);
	}
	private void initView() {
		mHandler = new Handler(this);
		pageTitle = (TextView) findViewById(R.id.kf_title);
		tabStockSn = (TextView) findViewById(R.id.tab_stock_sn);
		tv_title = ((TextView) findViewById(R.id.tv_title));
		findViewById(R.id.btn_refresh).setVisibility(View.GONE);
		findViewById(R.id.img_callback).setOnClickListener(this);
		cxButton = (Button) findViewById(R.id.btn_trust);
		cxButton.setVisibility(View.VISIBLE);
		cxButton.setOnClickListener(this);
		tableFixHeaders = (TableFixHeaders) findViewById(R.id.table_entrust);
		
//		mPullToRefreshListView = (PullToRefreshListView) findViewById(R.id.lv_stocks);
//		actualListView = mPullToRefreshListView.getRefreshableView();
//		registerForContextMenu(actualListView);
//		actualListView.setOnItemClickListener(itemClick);
		initData();
	}

	private void initData() {
		
		pageTitle.setText(R.string.title_entrust);
		tabStockSn.setText(R.string.gains);
		tv_title.setText(R.string.top_etrust);

		mUserStocks = new ArrayList<EntrustStock>();
//		mUserStocks = (ArrayList<EntrustStock>) getIntent()
//				.getSerializableExtra("userStock");
		datas = new ArrayList<EntrustStock>();
//		mAdapter = new EntrustStocksAdapter(getApplicationContext(), datas);
//		actualListView.setAdapter(mAdapter);
		mQueue = Volley.newRequestQueue(getApplicationContext());
		myApp = (MyApplication) getApplication();

		loadWT();
//		getStockDeals();
	}

	/**
	 * 查询今日委托列表
	 */
	private void loadWT() {
		datas.clear();
		String url = myApp.url + "Entrust.dll";
		final String t = KouFuTools.readTimeInfo(new String());
		cookieStringRequest = new CookieStringRequest(Request.Method.POST, url,
				new Response.Listener<String>() {

					@Override
					public void onResponse(final String response) {
						// 0:220917473346,000006,深振业Ａ,c,11.52,1,09:17:47 ,,,已报;
						// htxh,stock_code,stock_name,entrust_bs,price,amount,time,cj_price,cj_time,status;
						Log.w(TAG, "~~~~~~~~~~response~~~~~");
						Log.w(TAG, response);
						if (response != null && !response.equals("")) {
							if (response.substring(0, 1).equals("0")) { 
								new Thread(new  Runnable() {
									public void run() { 
										build(response);
									}
								}).start(); 

							} else if (response.substring(0, 1).equals("1")) {
								// 1:今日无委托纪录！
//								build("");
								tableFixHeaders.setVisibility(View.GONE);
								Toast.makeText(myApp, response.substring(2),
										Toast.LENGTH_SHORT).show();
							}
						} else {
							Toast.makeText(myApp, "异常数据", Toast.LENGTH_SHORT)
									.show();
						}
					}
				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {

					}
				}) {
			@Override
			protected Map<String, String> getParams() throws AuthFailureError {
				Map<String, String> params = new HashMap<String, String>();
				params.put("userid", myApp.getUserid());
				params.put("type", "0");
				params.put("time", t);
				return params;
			}

		};
		String cookie = KouFuTools.descrypt(myApp.getUserid() + t);
		cookieStringRequest.setHeader(cookie);
		cookieStringRequest.setCharset("gbk");
		mQueue.add(cookieStringRequest);
	}

	private void build(String response){
		if(!TextUtils.isEmpty(response)){
			response = response.substring(2);
			String[] list = response.split(";");
			for (String result : list) {
				String[] rs = result.split(",");
				EntrustStock stockInfo = new EntrustStock();
				stockInfo.htxh = rs[0];
				stockInfo.setStockId(rs[1]);
				stockInfo.setStockName(rs[2]);
				stockInfo.entrustBs = rs[3];
				stockInfo.price = (rs[4]);
				stockInfo.amount = (rs[5]);
				stockInfo.time = rs[6];
				stockInfo.cjPrice = rs[7];
				stockInfo.cjTime = rs[8];
				stockInfo.status = rs[9];
				datas.add(stockInfo);
			}
		}
//		EntrustStock s = new EntrustStock();
//		s.setStockName("张江传奇");
//		s.setStockId("123445");
//		s.setStockbj("12");
//		s.price = "8";
//		s.status = "已成";
//		s.entrustBs = "c";
//		s.amount = "100";
////		s.cjTime = "10:05";
//		datas.add(s);
//		datas.add(s);
//		"状态","股票名称","操作类型","委托价格","委托数量","委托时间"
		if(datas.size()>0){
			int size = datas.size()+1;
			table = new String[size][heads.length];
			EntrustStock entrustStock  = null;
			for(int i=0;i<size;i++){
				if(i>0){
					entrustStock = datas.get(i-1);
				}
				for(int j=0;j<heads.length;j++){
					if(i==0){
						table[i][j] = heads[j];
					}else{
						switch (j) {
						case 0:
							table[i][j] ="";
							break;
						case 1:
							table[i][j] = entrustStock.getStatus();
							
							break;
						case 2:
							table[i][j] = entrustStock.getStockName()+","+entrustStock.getStockId();
							
							break;
						case 3:
							table[i][j] = KouFuTools.getEntrustType(entrustStock.entrustBs); 
							 
							break;
						case 4:
							table[i][j] = (entrustStock.price);  
							 
							break;
						case 5:
							table[i][j] = (entrustStock.amount); 
							
							break;
						case 6:
							table[i][j] = entrustStock.time; 
							break;
						default:
							break;
						}
						
					}
				}
			}
		}
//		Log.e(TAG, table.toString());
		mHandler.obtainMessage(0x11).sendToTarget();
	}
	
 

	private void parseData() {
		if (mUserStocks.size() > 0 && datas.size() > 0) {
			HashMap<String, UserStocks> map = new HashMap<String, UserStocks>();
			for (UserStocks u : mUserStocks) {
				map.put(u.getStockId(), u);
			}
			for (EntrustStock stockInfo : datas) {
				if (mUserStocks.contains(stockInfo)) {
					UserStocks u = map.get(stockInfo.getStockId());
					Log.w(TAG, u.toString());
					stockInfo.setAllmoney(u.getAllmoney());
					stockInfo.setStockbj(u.getStockbj());
					stockInfo.setStockcyl(u.getStockcyl());
					stockInfo.setStockdqj(u.getStockdqj());
					stockInfo.setStockHold(u.getStockHold());
				}
			}
		}
	}
	/**
	 * 
	* @Title: postWTRequest 
	* @Description: 撤单方法 
	* @param     设定文件 
	* @return void    返回类型 
	* @throws
	 */
	private void postWTRequest(){
		if (cdlist != null) { 
			final EntrustStock stockInfo = datas.get(0);
			
				myApp = (MyApplication) getApplication();
				String url = myApp.url + Statics.Request_WT;
				final String t = KouFuTools.readTimeInfo(new String());
				cdStringRequest = new CookieStringRequest(Request.Method.POST,
						url, new Response.Listener<String>() {

							@Override
							public void onResponse(String response) {
								if (response != null && !response.equals("")) {
									String[] results = response.split(":");
									if (results[0].equals("0")) {
										Toast.makeText(getApplicationContext(),
												results[1], Toast.LENGTH_SHORT)
												.show();
									} else if (results[0].equals("1")) {
										// 1:您没有该股票或者卖出数量超出了可卖数，如有异议，请与管理员联系。
										Toast.makeText(getApplicationContext(),
												results[1], Toast.LENGTH_SHORT)
												.show();
									} 
									Log.d(TAG, response);
								}
							}
						}, new Response.ErrorListener() {

							@Override
							public void onErrorResponse(VolleyError error) {

							}
						}) {
					@Override
					protected Map<String, String> getParams()
							throws AuthFailureError {
						Map<String, String> params = new HashMap<String, String>();
						params.put("userid", myApp.getUserid());
						params.put("teamid", myApp.getGroupId());
						params.put("time", t);
						// msg：委托信息，格式：mmlb,stockcode,stockname,stocktype,zqlb,price,amount
						String sid = stockInfo.stockId;
						String sN = stockInfo.getStockName();
						String msg = new StringBuilder("d")
								.append(",")
								.append(sid)
								.append(",")
								.append(sN)
								.append(",")
								.append(KouFuTools.getEnCode(sid))
								.append(",")
								.append(KouFuTools.stockGetZQLB(
										Integer.parseInt(sid), sN)).append(",")
								.append(stockInfo.price).append(",")
								.append(stockInfo.amount).toString();
						params.put("msg", msg);
						Log.d(TAG, "~~~~~~~~msg==" + msg);
						return params;
					}

				};
				String cookie = KouFuTools.descrypt(myApp.getUserid() + t);
				cdStringRequest.setHeader(cookie);
				cdStringRequest.setCharset("GBK");
				cdStringRequest.setRequestCharset("GBK");
				mQueue.add(cdStringRequest);
			}
		 
	}

	private OnItemClickListener itemClick = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {

			Intent intent = new Intent(EntrustListActivity.this,
					EntrustOrCancleActivity.class);
			intent.putExtra("stockInfo", datas.get(position - 1));
			startActivity(intent);

		}
	};

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.img_callback:
			this.finish();
			break;
		case R.id.btn_trust: 
			if(cdlist!=null && cdlist.size()>0){
				EntrustStock stockInfo = datas.get(0);
				if(stockInfo.equals("已报")){  
					showWTDialog();
				} else{
					Toast.makeText(mContext, "不能撤单", Toast.LENGTH_SHORT).show();
				}
			}
			
			break;

		default:
			break;
		} 
	}
	private void showWTDialog(){
		final CofDialog dialog = new CofDialog(mContext, R.layout.dialog_cofool_txt);
		dialog.positive.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				postWTRequest(); 
			}
		});
		dialog.negative.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				dialog.dismiss(); 
			}
		});
		dialog.show();
	}
	@Override
	protected void onStop() {
		super.onStop();
		if (stringRequest != null) {
			mQueue.cancelAll(stringRequest);
		}
		if (cookieStringRequest != null) {
			mQueue.cancelAll(cookieStringRequest);
		}
	}

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case 0x11:
			if(table.length>0){
				tableFixHeaders.setVisibility(View.VISIBLE);
				entrustTableAdapter = new EntrustTableAdapter<String>(EntrustListActivity.this,table);
				tableFixHeaders.setAdapter(entrustTableAdapter);
				entrustTableAdapter.setOnItemClick(new OnTableItemClickIf() {
					
					@Override
					public void OnTableItemClickListener(int row,boolean isChecked) { 
						if(row==-1){
							return;
						}
						
						if(cdlist==null){
							cdlist = new ArrayList<String>();
						}
						if(cdlist.contains(row+"")){
							if(!isChecked){
								cdlist.remove(row+"");
							} 
						}else{
							if(isChecked){
								cdlist.add(row+"");
							}
						}  
					}
				});
			}
			break;

		default:
			break;
		}
		return false;
	}

}
